package api;

import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import model.ResultData;
import model.UserInfo;
import util.SessionUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 获得session，判断用户是否登录
 * @author: chengbaiyi
 * @create: 2022-06-26 13:17
 */
@WebServlet("/sess")
public class GetSessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state = -1;
        String data = "";
        String msg = "";
        UserInfo userInfo = SessionUtil.getSessionUserInfo(req);
        if (userInfo != null) {
            // 已登录
            state = 200;
            msg = "已经登录";
            data = userInfo.getUsername();
        } else {
            // 未登录
            data = "";
            msg = "未登录";
        }
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        resp.getWriter().println(
                JSONUtil.toJsonStr(new ResultData(state, data, msg))
        );
    }
}
